import axios from 'axios'
import { showLoading, hideLoading } from '@/utils/loading'
import { ElMessage } from 'element-plus'
import { useHandleLogin } from '../../store'
const loginTypeNum = useHandleLogin()
// import router from '../../router'
class Request {
    constructor(options = {}) {
        this.intance = axios.create(options)

        this.intance.interceptors.request.use(
            (config) => {
                const token = window.localStorage.getItem('token')
                if (token) {
                    config.headers.token = token
                }
                // 请求拦截进来调用显示loading效果
                showLoading()

                return config
            },
            (err) => {
                return Promise.reject(err)
            }
        )
        this.intance.interceptors.response.use(
            (res) => {
                // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
                setTimeout(() => {
                    hideLoading()
                }, 200)
                console.log('response res: ', res)
                const code = res.data.code
                if (code) {
                    ElMessage.error(res.data.msg)
                    if (code === 400) {
                        // 无效的token或者token已经过期~
                        window.localStorage.removeItem('token', '')
                        window.localStorage.removeItem('userInfo', '')
                        window.localStorage.removeItem('userRule', '')
                        loginTypeNum.value = 2
                        return
                    }
                }
                return res.data
            },
            (err) => {
                // 响应拦截进来隐藏loading效果，此处采用延时处理是合并loading请求效果，避免多次请求loading关闭又开启
                setTimeout(() => {
                    hideLoading()
                }, 200)

                return Promise.reject(err)
            }
        )
    }
    request(opt = {}) {
        return this.intance.request(opt)
    }
    post(data = {}) {
        return this.intance.request({
            ...data,
            method: 'post'
        })
    }
    get(data = {}) {
        return this.intance.request({
            ...data,
            method: 'get'
        })
    }
}

export default Request
